import React, { useEffect, useState, useImperativeHandle, useRef } from 'react';
import { Button, Modal, Form, Input, Select, message } from 'antd';
import MyUpload from '../myUpload';
import * as api from '@/api/product';
import { login } from '@/api/users';

type aa = {
  category_id: string;
  productName: string;
  price: number;
  description: string;
  inventory: number;
  imageUrl: string;
};

type Iprops = {
  getList: () => Promise<void>;
  isModalOpen: boolean;
  setIsModalOpen: (isModalOpen: boolean) => void;
  title: string;
  productId: string;
};

const MyModal = React.forwardRef<any, Iprops>((props, ref) => {
  // 解构从父组件传递来的数据
  let { getList, isModalOpen, productId, setIsModalOpen, title } = props;

  // 使用hook获取form实例
  let [loginForm] = Form.useForm();
  // const [isModalOpen, setIsModalOpen] = useState(false);
  // const [selectCategory,setSelectCategory] = useState<string>('lucy')
  const [loading, setLoading] = useState<boolean>(true);
  // 类目列表
  const [categoryList, setCategoryList] = useState<any[]>([]);
  // 上传图片地址
  const [imageUrl, setImageUrl] = useState<string>('');

  // 确定按钮
  const handleOk = () => {
    // setIsModalOpen(false);
    loginForm.submit(); // 让表单进行校验
    // console.log(loginForm)
  };

  // 取消按钮
  const handleCancel = () => {
    setIsModalOpen(false);
    // 清空表单
    loginForm.resetFields();
    // 清空图片
    setImageUrl('');
  };

  // 表单验证通过
  const onFinish = async (values: any) => {
    let res = null;

    if (title === '添加商品') {
      console.log(values);
      // 添加商品的请求
      let obj = {
        category_id: values.category_id.value,
        productName: values.productName,
        price: values.price,
        description: values.description,
        inventory: values.inventory,
        imageUrl: imageUrl,
      };

      try {
        res = await api.addProduct(obj);
        console.log(res);
      } catch (e) {
        console.log(e);
      }
    } else if (title === '修改商品') {
      // 修改商品的请求
      try {
        // console.log(imageUrl)
        let obj = {
          category_id: values.category_id,
          product_id: productId,
          productName: values.productName,
          price: values.price,
          description: values.description,
          inventory: values.inventory,
          imageUrl: imageUrl,
        };

        res = await api.updateProduct(obj);
      } catch (e) {
        console.log(e);
      }
    }
    // console.log(res)
    if (res!.data.state) {
      // 清空列表
      // 更新列表
      getList();
      // 成功提示框
      message.open({
        type: 'success',
        content: `${title}成功`,
      });
    } else {
      // 失败提示框
      message.open({
        type: 'error',
        content: `${title}失败`,
      });
    }
    // 清空表单
    loginForm.resetFields();
    // 清空图片
    setImageUrl('');
    // 关闭模态框
    setIsModalOpen(false);
  };

  // 表单验证不通过
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  // 选中商品类别
  const handleSelectCategory = (value: string, option: any) => {
    console.log('value', value);
    console.log('option', option);
  };

  // 将子组件的方法暴露给父组件
  useImperativeHandle(ref, () => {
    return {
      aaa: loginForm.setFieldsValue,
      bbb: setImageUrl,
    };
  });

  useEffect(() => {
    api.getCategory().then((res) => {
      let option = res.data.data.map((item: any) => ({
        label: item.categoryName,
        value: item.category_id,
      }));
      console.log(option);
      setCategoryList(option);
      setLoading(false);
    });
  }, []);

  return (
    <>
      <Modal
        title={title}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={loginForm}
          name="add-product"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="商品图片">
            <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl} />
          </Form.Item>
          <Form.Item
            label="商品类目"
            initialValue={categoryList[0]}
            name="category_id"
            rules={[{ required: true, message: '请输入商品类目' }]}
          >
            <Select
              // value={selectCategory}
              style={{ width: 150 }}
              onChange={handleSelectCategory}
              loading={loading}
              options={categoryList}
            />
          </Form.Item>
          <Form.Item
            label="商品名称"
            name="productName"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商品价格"
            name="price"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商品描述"
            name="description"
            rules={[{ required: true, message: '请输入商品描述' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商品库存"
            name="inventory"
            rules={[{ required: true, message: '请输入商品库存' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
});

export default MyModal;
